import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:management/app/cons.dart';
import 'package:management/model/department_model.dart';
import 'package:management/model/visit_matter_model.dart';
import 'package:management/utils/convert.dart';
import 'package:management/model/visitor_model.dart';
import 'package:management/utils/custom_router.dart';
import 'package:management/utils/log_utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:management/views/visitor/query/query_result.dart';

///按条件查询访客记录
class VisitorRecordQuery extends StatefulWidget {
  @override
  _VisitorRecordQueryState createState() => _VisitorRecordQueryState();
}

class _VisitorRecordQueryState extends State<VisitorRecordQuery> {
  /// 访客姓名控制器
  final TextEditingController _textEditingControllerName =
      TextEditingController();

  ///被访人 控制器
  final TextEditingController _textEditingControllerInterviewee =
      TextEditingController();

  ///车牌号码 控制器
  final TextEditingController _textEditingControllerLicensePlateNumber =
      TextEditingController();
  String? _sex;

  String? _visitMatter;

  String? _visitDepartment;

  String _hintTextStartTime = "请选择开始日期";
  String _hintTextEndTime = "请选择结束日期";
  String? _startDate;
  String? _endDate;

  bool indicatorVisible = false;

  List<Department> departments = [Department(Strings.nothing)];
  List<VisitMatter> matters = [VisitMatter(Strings.nothing)];

  @override
  void initState() {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
    super.initState();
    queryDepartmentAndVisitMatter();
  }

  Widget _buildDepartments() => Container(
        width: 700.w,
        padding: EdgeInsets.only(left: 10.w),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(5.w),
            topRight: Radius.circular(5.w),
            bottomLeft: Radius.circular(5.w),
            bottomRight: Radius.circular(5.w),
          ),
        ),
        child: DropdownButtonHideUnderline(
          child: DropdownButton(
            hint: Text(
              "请选择被访部门",
              style: TextStyle(fontSize: 20.sp),
            ),
            value: _visitDepartment,
            items: departments
                .map(
                  (e) => DropdownMenuItem(
                      value: e.name,
                      child: Text(
                        e.name!,
                        style: TextStyle(fontSize: 22.sp),
                      )),
                )
                .toList(),
            onChanged: (value) {
              setState(() {
                _visitDepartment = value.toString();
              });
            },
          ),
        ),
      );

  Widget _buildVisitMatters() => Container(
        width: 700.w,
        padding: EdgeInsets.only(left: 10.w),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(5.w),
            topRight: Radius.circular(5.w),
            bottomLeft: Radius.circular(5.w),
            bottomRight: Radius.circular(5.w),
          ),
        ),
        child: DropdownButtonHideUnderline(
          child: DropdownButton(
            hint: Text(
              "请选择来访事由",
              style: TextStyle(fontSize: 20.sp),
            ),
            value: _visitMatter,
            items: matters
                .map((e) => DropdownMenuItem(
                      value: e.matter,
                      child: Text(
                        e.matter!,
                        style: TextStyle(fontSize: 22.sp),
                      ),
                    ))
                .toList(),
            onChanged: (value) {
              setState(() {
                _visitMatter = value.toString();
              });
            },
          ),
        ),
      );

  AppBar _buildAppBar() => AppBar(
        leading: IconButton(
          onPressed: () => Navigator.of(context).pop(),
          icon: Icon(Icons.arrow_back),
          iconSize: 35,
        ),
        title: Text(
          "记录查询",
          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25.sp),
        ),
        centerTitle: true,
        actions: [
          Padding(
            padding: EdgeInsets.only(right: 10.w),
            child: IconButton(
              tooltip: "查询",
              icon: Icon(Icons.search_sharp),
              iconSize: 45.w,
              onPressed: () {
                _recordQuery();
              },
            ),
          )
        ],
        backgroundColor: Colors.blue,
      );

  Widget _buildBody() => Container(
        color: Colors.black12,
        child: ListView(
          children: [
            Container(
              width: MediaQuery.of(context).size.width,
              // height: MediaQuery.of(context).size.height,
              alignment: Alignment.topCenter,
              padding: EdgeInsets.all(20.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "查询条件",
                    style:
                        TextStyle(fontWeight: FontWeight.bold, fontSize: 25.sp),
                  ),
                  Container(
                    width: 0.9.sw,
                    height: 0.3.sh,
                    padding: EdgeInsets.all(20.w),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12.w),
                        border: Border.all(color: Colors.grey, width: 2.w),
                        color: Colors.white),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          height: 50.h,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "访客姓名",
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 25.sp),
                              ),
                              Container(
                                width: 700.w,
                                child: TextField(
                                  controller: _textEditingControllerName,
                                  style: TextStyle(fontSize: 25.sp),
                                  textAlignVertical: TextAlignVertical.center,
                                  decoration: InputDecoration(
                                      hintText: "请输入访客姓名",
                                      hintStyle: TextStyle(fontSize: 20.sp),
                                      border: OutlineInputBorder()),
                                ),
                              ),
                              Text(
                                "性        别",
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 25.sp),
                              ),
                              Container(
                                width: 700.w,
                                padding: EdgeInsets.only(left: 10.w),
                                decoration: BoxDecoration(
                                  border: Border.all(color: Colors.grey),
                                  borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(5.w),
                                    topRight: Radius.circular(5.w),
                                    bottomLeft: Radius.circular(5.w),
                                    bottomRight: Radius.circular(5.w),
                                  ),
                                ),
                                child: DropdownButtonHideUnderline(
                                  child: DropdownButton(
                                    hint: Text(
                                      "请选择性别",
                                      style: TextStyle(fontSize: 20.sp),
                                    ),
                                    value: _sex,
                                    items: [
                                      DropdownMenuItem(
                                        child: Text(
                                          "男",
                                          style: TextStyle(
                                            fontSize: 25.sp,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        value: "男",
                                      ),
                                      DropdownMenuItem(
                                        child: Text(
                                          '女',
                                          style: TextStyle(
                                            fontSize: 25.sp,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        value: "女",
                                      ),
                                    ],
                                    onChanged: (v) {
                                      setState(() => _sex = v.toString());
                                    },
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          height: 50.h,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "被访部门",
                                style: TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 25),
                              ),
                              _buildDepartments(),
                              Text(
                                "被  访  人",
                                style: TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 25),
                              ),
                              Container(
                                width: 700.w,
                                child: TextField(
                                  controller: _textEditingControllerInterviewee,
                                  textAlignVertical: TextAlignVertical.bottom,
                                  style: TextStyle(fontSize: 20),
                                  decoration: InputDecoration(
                                      hintText: "请输入被访人",
                                      hintStyle: TextStyle(fontSize: 20),
                                      border: OutlineInputBorder()),
                                ),
                              )
                            ],
                          ),
                        ), //被访部门
                        Container(
                          height: 50.w,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "来访事由",
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 25.sp),
                              ),
                              Container(
                                width: 700.w,
                                child: _buildVisitMatters(),
                              ),
                              Text(
                                "车牌号码",
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 25.sp,
                                ),
                              ),
                              Container(
                                width: 700.w,
                                child: TextField(
                                  controller:
                                      _textEditingControllerLicensePlateNumber,
                                  textAlignVertical: TextAlignVertical.bottom,
                                  style: TextStyle(fontSize: 20.sp),
                                  decoration: InputDecoration(
                                      hintText: "请输入车牌号码",
                                      hintStyle: TextStyle(fontSize: 20.sp),
                                      border: OutlineInputBorder()),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          height: 50.w,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "开始日期",
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 25.sp),
                              ),
                              _buildTime(_hintTextStartTime, 1),
                              Text(
                                "结束日期",
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 25.sp,
                                ),
                              ),
                              _buildTime(_hintTextEndTime, 0),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(top: 30),
              child: Visibility(
                visible: indicatorVisible,
                child: Container(
                  width: 80,
                  height: 80,
                  child: CircularProgressIndicator(
                    strokeWidth: 5,
                    backgroundColor: Colors.white.withAlpha(33),
                  ),
                ),
              ),
            )
          ],
        ),
      );

  void queryDepartmentAndVisitMatter() async {
    departments = (await DepartmentProvider().queryAll())!;
    if (departments == null) {
      departments = [];
    }

    matters = (await VisitMatterProvider().queryAll())!;
    if (matters == null) {
      matters = [];
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(),
      body: _buildBody(),
    );
  }

  ///[startOrEnd] 用来区别是 登记日期 还是 结束日期
  Widget _buildTime(String value, int startOrEnd) => Container(
        width: 700.w,
        child: TextField(
          decoration: InputDecoration(
            hintText: value,
            hintStyle: TextStyle(fontSize: 20.sp),
            border: OutlineInputBorder(),
          ),
          textAlignVertical: TextAlignVertical.bottom,
          style: TextStyle(fontSize: 20.sp),
          readOnly: true,
          onTap: () async {
            DateTime? tmpDate = await showDatePicker(
              context: context,
              initialDate: DateTime.now(),
              firstDate: DateTime(2021),
              lastDate: DateTime.now(),
              locale: Locale.fromSubtags(languageCode: 'zh'),
            );
            if (tmpDate != null) {
              setState(() {
                switch (startOrEnd) {
                  case 1:
                    _startDate = Convert.format(tmpDate);
                    _hintTextStartTime = Convert.format(tmpDate);
                    break;
                  case 0:
                    _endDate = Convert.format(tmpDate);
                    _hintTextEndTime = Convert.format(tmpDate);
                    break;
                }
              });
            }
          },
        ),
      );

  ///根据条件查询
  void _recordQuery() async {
    //获取查询条件 字段内容
    String name = _textEditingControllerName.text;
    String interviewee = _textEditingControllerInterviewee.text;
    String lpn = _textEditingControllerLicensePlateNumber.text;
    MyLog.i("""查询条件
    访客姓名：$name    性别：$_sex
    被访部门：$_visitDepartment    被访人：$interviewee
    来访事由：$_visitMatter    车牌号码：$lpn
    开始日期：$_startDate    结束日期：$_endDate""");

    //   LogUtil.d("""查询条件
    //   访客姓名：$name    性别：$_sex
    //   被访部门：$_visitDepartment    被访人：$interviewee
    //   来访事由：$_visitMatter    车牌号码：$lpn
    //   开始日期：$_hintTextStartTime    结束日期：$_hintTextEndTime""",
    //       tag: "VisitorRecordQuery");
    setState(() {
      indicatorVisible = true;
    });
    List<Visitor>? allVisitor =
        await VisitorProvider.provider.getVisitorByCondition(
      name: name,
      gender: _sex,
      departmentInterviewee: _visitDepartment,
      interviewee: interviewee,
      visitMatter: _visitMatter,
      licensePlateNumber: lpn,
      startDate: _startDate,
      endDate: _endDate,
    );
    setState(() {
      indicatorVisible = false;
    });
    MyLog.i("查询到的记录数目：${allVisitor == null ? null : allVisitor.length}");
    // Navigator.of(context).pushNamed('/QueryResult', arguments: allVisitor);
    Navigator.push(
        context, SlideRoute(QueryResult(visitorRecords: allVisitor)));
  }
}
